﻿using Grpc.Net.Client.Balancer;
using Nacos.V2;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Zy.Shared.Rpc.GrpcBase
{
    /// <summary>
    /// 静态解析器工厂
    /// </summary>
    /// <param name="nacosNaming"></param>
    public class ZyStaticResolverFactory(
    INacosNamingService nacosNaming)
    {
        private Dictionary<string,StaticResolverFactory> staticResolverFactorys;
        public async Task<StaticResolverFactory> GetFactoryInstanceAsync(string serviceName, string groupName)
        {
            if (!staticResolverFactorys.TryGetValue(serviceName,out StaticResolverFactory resolverFactory))
            {
                var instances = await nacosNaming.GetAllInstances(serviceName,groupName);
                var addrs = instances.Select(x => new BalancerAddress(x.Ip, x.Port)).ToArray();
                resolverFactory = new StaticResolverFactory(addr => addrs);
                staticResolverFactorys.Add(serviceName, resolverFactory);
            }
            return resolverFactory;
        }
    }

}
